/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kunzisoft.switchdatetime.provider;


import com.kunzisoft.switchdatetime.ResourceTable;
import com.kunzisoft.switchdatetime.event.MessageEvent;

import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.app.Context;

import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import org.greenrobot.eventbus.EventBus;


import java.util.Calendar;


public class CalendarProvider extends BaseItemProvider {
    private Context context;
    private Calendar calendar;
    private int current_month = 0;
    private int original_year;
    private int original_month;
    private int original_day;
    private int year;
    private int month;
    private int day;
    private int dayOfWeek;
    private int firstWeekOffset = 0;
    private int offset = 0;
    private ViewHolder viewHolder = null;
    private DependentLayout lastview = null;
    private boolean isCk = true;
    private boolean isCurrentMonth;
    private boolean isOrientation;

    /**
     * 构造方法
     *
     * @param context context
     * @param calendar calendar
     */
    public CalendarProvider(Context context, Calendar calendar) {
        this.context = context;
        this.calendar = calendar;
        original_year = calendar.get(Calendar.YEAR);
        original_month = calendar.get(Calendar.MONTH);
        original_day = calendar.get(Calendar.DAY_OF_MONTH);
        current_month = calendar.get(Calendar.MONTH);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        firstWeekOffset = Calendar.SATURDAY - dayOfWeek + 1;
        offset = firstWeekOffset - 7;

//        System.out.println("-->>CalendarProvider."+original_year+"--"+original_month+"--"+original_day);

        // 获取保存的手机横竖屏情况（true - 竖屏；false - 横屏）
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences orientation = databaseHelper.getPreferences("ori_pref");
        isOrientation = orientation.getBoolean("orientation", true);
    }

    @Override
    public int getCount() {
        return 49;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public Component getComponent(int position, Component componentP, ComponentContainer componentContainer) {
        Component component = componentP;
        if (component == null) {
            // 获取当前布局
            int xmlId;
            if (isOrientation) {
                xmlId = ResourceTable.Layout_calendar_item_layout;
            } else {
                xmlId = ResourceTable.Layout_calendar_item_layout_land;
            }
            component = LayoutScatter.getInstance(context)
                    .parse(xmlId, null, false);
            viewHolder = new ViewHolder();
            component.setTag(viewHolder);
        } else {
            if (component.getTag() instanceof ViewHolder) {
                viewHolder = (ViewHolder) component.getTag();
            }
        }
        if (viewHolder != null) {
            viewHolder.item_root = (DependentLayout) component.findComponentById(ResourceTable.Id_item_root);
            viewHolder.item_text = (Text) component.findComponentById(ResourceTable.Id_item_text);
            viewHolder.item_background = (Image) component.findComponentById(ResourceTable.Id_item_background);
            setData(position, viewHolder);
            viewHolder.item_root.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {

                    if (position < 7) {
                        return;
                    }
                    if (lastview == null) {
                        lastview = (DependentLayout) component;
                    }
                    clearBackground(lastview);
                    Image image = (Image) component.findComponentById(ResourceTable.Id_item_background);
                    image.setVisibility(Component.VISIBLE);
                    Text item_text = (Text) component.findComponentById(ResourceTable.Id_item_text);
                    item_text.setTextColor(Color.WHITE);
                    lastview = (DependentLayout) component;
                    EventBus.getDefault().post(new MessageEvent(item_text.getText()));
                }
            });
        }
        return component;
    }

    class ViewHolder {
        private DependentLayout item_root;
        private Text item_text;
        private Image item_background;
    }

    private void setData(int position, ViewHolder viewHolder) {
        switch (position) {
            case 0:
                viewHolder.item_text.setText("Sun");

                break;
            case 1:
                viewHolder.item_text.setText("Mon");
                break;
            case 2:
                viewHolder.item_text.setText("Tue");
                break;
            case 3:
                viewHolder.item_text.setText("Wed");
                break;
            case 4:
                viewHolder.item_text.setText("Thu");
                break;
            case 5:
                viewHolder.item_text.setText("Fir");
                break;
            case 6:
                viewHolder.item_text.setText("Sat");
                break;
            default:
                break;
        }
        if (position < 7) {
            return;
        }
        resetCalendar();
        calendar.add(Calendar.DAY_OF_YEAR, offset);
        offset++;
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        isCurrentMonth = isCurrentMonth(month);
        viewHolder.item_text.setText(String.valueOf(day));


        if (!isCurrentMonth) {
            viewHolder.item_text.setTextColor(Color.GRAY);
            viewHolder.item_root.setEnabled(false);
        } else {
            viewHolder.item_root.setEnabled(true);
        }
    }

    private void resetCalendar() {
        calendar.set(original_year, original_month, original_day);
    }

    private boolean isCurrentMonth(int month) {
        return current_month == month;
    }

    private void clearBackground(DependentLayout lastview) {
        Image image = (Image) lastview.findComponentById(ResourceTable.Id_item_background);
        image.setVisibility(Component.HIDE);
        Text item_text = (Text) lastview.findComponentById(ResourceTable.Id_item_text);
        item_text.setTextColor(Color.BLACK);
    }
}